package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"unlimited-comments/api/request"
	"unlimited-comments/consts"
	"unlimited-comments/internal/model"
	"unlimited-comments/pkg"
)

func RegisterUser(c *gin.Context) {

	var req request.RegisterUserForm
	var user model.User

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	user.Mobile = req.Mobile
	err := user.MobileByUser()
	if err != nil {
		return
	} else {
		if user.Id != 0 {
			c.JSON(http.StatusOK, gin.H{
				"code":    100000,
				"message": "注册失败",
				"data":    "",
			})
			return
		}
		user.Password = pkg.Md5(req.Password)
		user.Name = req.Name

		err := user.RegisterUser()
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code":    100000,
				"message": "注册失败",
				"data":    "",
			})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"code":    http.StatusOK,
			"message": "注册成功",
			"data":    user.Name,
		})
	}

}

func LoginUser(c *gin.Context) {
	var req request.LoginUserForm
	var user model.User

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	user.Mobile = req.Mobile
	err := user.MobileByUser()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "登录失败",
			"data":    "",
		})
		return
	} else {
		if user.Id == 0 {
			c.JSON(http.StatusOK, gin.H{
				"code":    100000,
				"message": "账号或密码错误",
				"data":    "",
			})
			return
		}

		if user.Password != pkg.Md5(req.Password) {
			c.JSON(http.StatusOK, gin.H{
				"code":    100000,
				"message": "账号或密码错误",
				"data":    "",
			})
			return
		}

		token := pkg.CreateJwtToken(user.Id, 3*(24*time.Hour), consts.JWT_KEY)

		c.JSON(http.StatusOK, gin.H{
			"code":    http.StatusOK,
			"message": "登录成功",
			"data":    token,
		})
	}
}

func GoOutUser(c *gin.Context) {

}
